package com.jw.qme.utils;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;

public class RSAKeyTest {

    public static void main(String[] args) {
        try {
            // 公钥和私钥
            String publicKeyPEM = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4hTrrdvaYIT+sFVYn+w50HtLmq6ZDGNcwGS8PRC+zGncUvpvhkpYwZVmzQ6FVgbQ2DfY7DXv39Wb1gcWwPwcS/R+ujoP9H2Tq4V1s0t6n1MKykdaQUmv8ybJChwnsyue3x2lq4h5nUpY7MG0hmBTR3l9nEDZfEshtsvligpk18pqj0f0eY3KDiSPpISObnwZ5mgx1Rrh4glThMQyQKp1/RH4VC/qVWSeNTju87DsQkzwSLueo4/ok78Js1BttFCSR/bQWIA4dXSyD80ZGD9spzuZ1A4hELo5YF/Q99uC5CSGr4J6p9L67mEBHnpY2wwbGYPuYX/4Dg7aL80qLAkm0wIDAQAB";
            String privateKeyPEM = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDiFOut29pghP6w\n" +
                    "VVif7DnQe0uarpkMY1zAZLw9EL7MadxS+m+GSljBlWbNDoVWBtDYN9jsNe/f1ZvW\n" +
                    "BxbA/BxL9H66Og/0fZOrhXWzS3qfUwrKR1pBSa/zJskKHCezK57fHaWriHmdSljs\n" +
                    "wbSGYFNHeX2cQNl8SyG2y+WKCmTXymqPR/R5jcoOJI+khI5ufBnmaDHVGuHiCVOE\n" +
                    "xDJAqnX9EfhUL+pVZJ41OO7zsOxCTPBIu56jj+iTvwmzUG20UJJH9tBYgDh1dLIP\n" +
                    "zRkYP2ynO5nUDiEQujlgX9D324LkJIavgnqn0vruYQEeeljbDBsZg+5hf/gODtov\n" +
                    "zSosCSbTAgMBAAECggEBANT7uHt1XukG4ZjlDjS6qkyJmtQCIBTXlo15WQx+NgEE\n" +
                    "yZcybtYoPC1CvjH3uA0vJphLJISC25QW/FRJIVp1J4M2thxijp1ZoEA53oQmW0K1\n" +
                    "TLj7Nz/CV4vNwh9QHuZf9a9jkqtiSo+vds60PYlKPapb/cWyIjFB5mT6+SduW0od\n" +
                    "lbUmog0qtVAQxQiTXrRPwSK5rdCt+Yq/OEj+0RI4UUtk4Q3n+raLNz1D9zXgOjwR\n" +
                    "M3vWtsHtg9BgB1xk0rosla7Z1TUvGa+hEZuY+7RyOUetsyOrptDnGL43Q3EoVgP2\n" +
                    "3SmSqtf6Ps8RPEZCUaVEk+w14vQkh4UESElf9+PLmoECgYEA8LydyL5986EK+4Qo\n" +
                    "yLp4sJZEJ1BLBXmwwDeiZZz6C23VhK2d5qSBglYthOn7a1o1/owRAocH48dQmUVi\n" +
                    "m9YiWgPllQfd/Lqr//rw0tW1skxS967vcnQ9Mu8Ufwg2v7bS+wrSwX4wkzc2n3Cf\n" +
                    "XPF1ILP4HOVTBvEEewpHjlcrVwMCgYEA8GpwWz/geaakwte6ZYYtSML8Jnj0PaE/\n" +
                    "kXWa1Ua4eplcaRczDw7rgqrWDlx5UErxUDAo9yGKAHY8e/RnqW+oCs6PTJnw7+N5\n" +
                    "S3rNSKztWdoKzgZofqBpSAiSe3tDRnOSZA0tSrDnF2sz9Eg1JOn6hTtteE/gmW9j\n" +
                    "paD8EzMbv/ECgYBy7/r9b0W/XjJaJ505SR56YSQlCQbolFM5UtasYShY8JWzBRmQ\n" +
                    "lxZmXjLZdMVfWfDRmZo9dK7lp7Hpm+EaukAobhfc8aahFZctXmhAoVxgxmQOcW1N\n" +
                    "XgYiHVfR1uAc5HMS/PXnABK9Fu1zblgIDhh4BrT9Rtg/Ri93d072vNOqdQKBgFPl\n" +
                    "cOwG8HjDVH/B9IP1PNxFXuS2FNVk7d/+4FdI5Juz5PGvbNv2Yu0oXKaKUrNYU7md\n" +
                    "9M244IWkvRqsgXg5RLTwvEUI+3FbOjrC0dxorDNMybR3vANkSxkeFLAOpb1yG0Xa\n" +
                    "61FDRoF/oZO/lvwYwpm30U3I4iHpIybrdMvma+qhAoGAS1LzVL3WLtJApkwduZ2x\n" +
                    "TChNEEHgVxWNlCcb2Hs7ifpuHxwQpRnei4dstsGo1Xw+p86IRpzJbiEUJI4ul3wN\n" +
                    "zidBHtEqH21WGrbHP4rr1va+sMFWg7jZ/n0TNVzi+ZfCtjLeRY/sXoGBgV89FsDZ\n" +
                    "0k9liJTqIPZ1S274qD+xZsk=";

            // 加载公钥
            PublicKey publicKey = loadPublicKey(publicKeyPEM);

            // 加载私钥
            PrivateKey privateKey = loadPrivateKey(privateKeyPEM);

            // 原始数据
            String originalData = "Hello, RSA!";

            // 使用公钥加密
            String encryptedData = encrypt(publicKey, originalData);
            System.out.println("Encrypted Data: " + encryptedData);

            // 使用私钥解密
            String decryptedData = decrypt(privateKey, encryptedData);
            System.out.println("Decrypted Data: " + decryptedData);

            // 验证解密后的数据是否与原始数据一致
            if (originalData.equals(decryptedData)) {
                System.out.println("Public and Private keys match!");
            } else {
                System.out.println("Public and Private keys do not match!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 加载公钥
    public static PublicKey loadPublicKey(String pemPublicKey) throws Exception {
        String publicKeyPEM = pemPublicKey
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s+", "");
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyPEM);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    }

    // 加载私钥
    public static PrivateKey loadPrivateKey(String pemPrivateKey) throws Exception {
        String privateKeyPEM = pemPrivateKey
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", "");
        byte[] keyBytes = Base64.getDecoder().decode(privateKeyPEM);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(spec);
    }

    // 使用公钥加密数据
    public static String encrypt(PublicKey publicKey, String data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 使用私钥解密数据
    public static String decrypt(PrivateKey privateKey, String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}